package com.RKB.web;

import com.RKB.pojo.*;
import com.RKB.service.questionbankService;
import com.RKB.api.AjaxResult;
import com.RKB.service.AnswerResultService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.RKB.utils.switchTypes;

import java.util.*;
import java.util.stream.Collectors;


@CrossOrigin //允许跨域请求 springboot原生不支持跨域。
@RestController
public class QuestionbankController {
    @Autowired
    private questionbankService questionbankservice;
    @Autowired
    private AnswerResultService answerResultService;
//    utils工具类
    private switchTypes switchTypes = new switchTypes();


    /**
     * 查找题库所有内容
     *
     * @return
     */
    //@CrossOrigin(origins = "http://localhost:8080/Test/findAll")
    @RequestMapping("/findAll")
    public AjaxResult<List> findAll() {
        List<questionbank> list = questionbankservice.findAll();
        System.out.println("successful");
        AjaxResult<List> result = new AjaxResult<>();
        result.setCode(200);
        result.setMsg("成功");
        result.setData(list);
        return result;
    }

    /**
     * 根据问题查找
     *
     * @param question
     * @return
     */
    //@CrossOrigin(origins = "http://localhost:8080/Test/findAll")
    @RequestMapping("/findByQuestion")
    public AjaxResult<List> findByQuestion(String question) {
        List<questionbank> list = questionbankservice.findByQuestion(question);
        AjaxResult<List> result = new AjaxResult<>();
        result.setCode(200);
        result.setMsg("成功");
        result.setData(list);
        System.out.println("successful");
        return result;
    }

    /**
     * 根据题型查找
     *
     * @param type
     * @return
     */
    @RequestMapping("/findByType")
    public AjaxResult<List> findByType(String type) {
        AjaxResult<List> result = new AjaxResult<>();
        List<questionbank> list = questionbankservice.findByType(type);
        result.setCode(200);
        result.setMsg("成功");
        result.setData(list);
        return result;
    }

    /**
     * 根据id查找
     *
     * @param id
     * @return
     */
    @RequestMapping("/findById")
    public AjaxResult<List> findById(Integer id) {
        AjaxResult<List> result = new AjaxResult<>();
        List<questionbank> list = questionbankservice.findById(id);
        result.setCode(200);
        result.setMsg("成功");
        result.setData(list);
        return result;
    }


    /*
     * 这个接口用来测试前端返回用户答题结果得数据分析处理（创建的题库的题的数量很少）
     * @return
     */
    @RequestMapping("/titleTest")
    public AjaxResult<List> titleTest(){
        AjaxResult<List> result = new AjaxResult<>();
        List<questionbank> list = questionbankservice.findById(5);
        List<questionbank> list1 = questionbankservice.findById(6);
        List<questionbank> list2 = questionbankservice.findById(7);
        list.add(list1.get(0));
        list.add(list2.get(0));
        result.setCode(200);
        result.setMsg("成功");
        result.setData(list);
       // System.out.println(list);
        return result;
    }

@RequestMapping("/createExsercise")
    public AjaxResult<List> exsercise(){
    AjaxResult<List> result = new AjaxResult<>();
    Random random = new Random();
    HashSet<Integer> set = new HashSet<>();

    while(set.size()<18){
        set.add(Math.abs(random.nextInt())%75);
    }
    Iterator<Integer> iterator = set.iterator();
    ArrayList<questionbank> list = new ArrayList<>();
//    生成18道题为一组的练习题
    for (int i = 0; i < 18; i++) {
        list.add(questionbankservice.findById(iterator.next()).get(0));
    }


    //System.out.println(set);
    result.setCode(200);
    result.setMsg("success");
    result.setData(list);
    return result;
}



    /**
     * 创建题库  (利用set集合自动去重进行题库的组建)
     * 组题库
     *
     * @return
     */
    @RequestMapping("/createTitle")
    public AjaxResult<List> createTitle() {
        AjaxResult<List> result = new AjaxResult<>();
        List<Integer> type_OperationSystem = questionbankservice.findIdByType("嵌入式中级-操作系统"); //  2
        List<Integer> type_StorageSystem = questionbankservice.findIdByType("嵌入式中级-存储系统");  //  2
        List<Integer> type_InstructionSystem = questionbankservice.findIdByType("嵌入式中级-指令系统");  //  2
        List<Integer> type_DevelopmentAndDesign = questionbankservice.findIdByType("嵌入式中级-开发设计");  //  2
        List<Integer> type_Multimedia = questionbankservice.findIdByType("嵌入式中级-多媒体");  //  1
        List<Integer> type_FundamentalsOfComputer = questionbankservice.findIdByType("嵌入式中级-计算机基础");  //  1

        //System.out.println(type_DevelopmentAndDesign);

        Random random = new Random();
        int num;

        HashSet<Integer> titleSet = new HashSet<>();

        for (int i = 0; i < 10; i++) {  //操作系统
            num = random.nextInt();
            titleSet.add(type_OperationSystem.get(Math.abs(num % type_OperationSystem.size())));
//            System.out.println(Math.abs(num % type_OperationSystem.size()));
            if (titleSet.size() == 2) {
                break;
            }
        }
        for (int i = 0; i < 10; i++) {  //存储系统
            num = random.nextInt();
            titleSet.add(type_StorageSystem.get(Math.abs(num % type_StorageSystem.size())));
            if (titleSet.size() == 4) {
                break;
            }
        }
        for (int i = 0; i < 10; i++) {  //指令系统
            num = random.nextInt();
            titleSet.add(type_InstructionSystem.get(Math.abs(num % type_InstructionSystem.size())));
            if (titleSet.size() == 6) {
                break;
            }
        }
        for (int i = 0; i < 10; i++) {  //开发设计
            num = random.nextInt();
            titleSet.add(type_DevelopmentAndDesign.get(Math.abs(num % type_DevelopmentAndDesign.size())));
            if (titleSet.size() == 8) {
                break;
            }
        }
        for (int i = 0; i < 10; i++) {  //多媒体
            num = random.nextInt();
            titleSet.add(type_Multimedia.get(Math.abs(num % type_Multimedia.size())));
            if (titleSet.size() == 9) {
                break;
            }
        }
        for (int i = 0; i < 10; i++) {   //计算机基础
            num = random.nextInt();
            titleSet.add(type_FundamentalsOfComputer.get(Math.abs(num % type_FundamentalsOfComputer.size())));
            if (titleSet.size() == 10) {
                break;
            }
        }

        Iterator<Integer> titleSetIterator = titleSet.iterator();

        List<questionbank> title = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            title.add(questionbankservice.findById(titleSetIterator.next()).get(0));
        }
        //System.out.println(title);
        result.setCode(200);
        result.setMsg("成功");
        result.setData(title);
        return result;
    }

    /**
     * 做题结果正误的判断
     *
     * @param list
     * @return
     */
    @RequestMapping("/answerResult")
    public AjaxResult<List> answerResult(@RequestBody List<answerType> list) {
        ArrayList<Integer> error = new ArrayList<>();
        AjaxResult<List> result = new AjaxResult<>();

        Map<Integer, String> userCorrectMap = list.stream().
                collect(Collectors.toMap(answerType::getId, answerType::getCorrect));  //  用户答题结果list转换为map

        Set<Integer> userCorrectMapKeys = userCorrectMap.keySet(); //  用户答题结果的keys

        List<answerType> correct = questionbankservice.findCorrect();  //  查询题库全部题的正确答案

        Map<Integer, String> trueCorrectMap = correct.stream().
                collect(Collectors.toMap(answerType::getId, answerType::getCorrect));  //  题库所有答案list转换为map

        //System.out.println(trueCorrectMap);
        // System.out.println(userCorrectMap);  {1=A, 2=B}
        // System.out.println(integers);    [1, 2]

        Iterator<Integer> userCorrectMapKeysIterator = userCorrectMapKeys.iterator();  //用户答题结果迭代器
        int id;//用户答题的每道题的id
        String allType;
        int AllTypeNum;
        for (int i = 0; i < userCorrectMapKeys.size(); i++) {
            id = userCorrectMapKeysIterator.next();
            if (!trueCorrectMap.get(id).equals(userCorrectMap.get(id))) {
                error.add(id);//添加错题序号
            }
//            这里是做了题的id，无论对错都记录入表
            String typeById = questionbankservice.findTypeById(id);
            //System.out.println(typeById);

            //            这里就是区分答的题与答了并答错的题，加了num就是答了题的类型
            allType = switchTypes.switchtoAllType(typeById);

//            这里就是统计该类型的题答了多少道
            AllTypeNum = answerResultService.findErrorNum(allType, "root")+1;
//            这里是更新该类型的题目答了多少道
            answerResultService.updataErrorNum(allType,AllTypeNum,"root");
        }



        // public void updataErrorType(String errorType,Double score,String uid);
        // public void updataErrorNum(String errorType_num,Integer num,String uid);
        // public Integer findErrorTypeScore(String errorType,String uid);
        //public Integer findErrorNum(String ErrorNum,String uid);


        int errorNum;
        // System.out.println("error = "+error);    //这是错题的id  error是一个list集合;
        for (int i = 0; i < error.size(); i++) {
            String errorType = questionbankservice.findTypeById(error.get(i));

            //System.out.println(errorType);
            errorType = switchTypes.switchtoErrorType(errorType);
            //System.out.println(errorType);
            //System.out.println(ErrorNum);
            //System.out.println(ErrorNum.equals("StorageSystem_num"));
            //Integer errorNum = answerResultService.findErrorNum(ErrorNum,"root");
            //System.out.println(errorNum);
            errorNum = answerResultService.findErrorTypeScore(errorType,"root")+1;
            answerResultService.updataErrorTypeScore(errorType,errorNum,"root");
        }

//        用于向错误记录表中插入错误记录
        Err_log errLog = new Err_log();
        String errList = "";
        for (int i = 0; i < error.size(); i++) {
                errList += error.get(i).toString()+",";
        }
        String substring = errList.substring(0, errList.length()-1);
        errLog.setUser_id("root");
        errLog.setError_id(substring);
        questionbankservice.insertErr_log(errLog);
//        ---------------------------------------------------------------
        //System.out.println(userCorrectMap);
        //System.out.println(userCorrectMapKeys);

        result.setCode(200);
        result.setMsg("成功");
        result.setData(null);
        return result;
    }



    /**
     * 增加问题
     *
     * @param addquestion
     * @return
     */
    @RequestMapping("/toAddQuestion")
    public String toAddQuestion(questionbank addquestion) {
        questionbankservice.toAddQuestion(addquestion);
        System.out.println("successful");
        return "successful";
    }

//    查询七天以内的所有错题
    @RequestMapping("/getAllErr_questions")
    public AjaxResult<List<Err_questions_time>> getAllErr_questions(String username){
        List<Err_questions_time> errQuestionbank = questionbankservice.getErr_questionbank(username);
        AjaxResult<List<Err_questions_time>> ajaxResult = new AjaxResult<>();
        ajaxResult.setData(errQuestionbank);
        ajaxResult.setCode(200);
        ajaxResult.setMsg("成功");
        return ajaxResult;
    }

}
